const _ = require('lodash')
const os = require('os');
const path = require('path');
const configFile = path.join(os.homedir(), '.das', 'dasconfig.json');
var fileConfig = require(configFile);

var config = module.exports = {}

// global config
config.encryptLog = fileConfig.EncryptLog || false;
config.watchdog = fileConfig.WatchDog || false;
config.mqtt = {
  enterpriseNo: fileConfig.Enterprise.Id,
  serialNo: fileConfig.Enterprise.SerialNo,
  deviceId: fileConfig.Enterprise.DeviceId,
  serverUrl: fileConfig.Server,
  username: fileConfig.Username,
  password: fileConfig.Password

}

config.modbus = {
  comName: fileConfig.comName || '/dev/ttyUSB0',
  samplingInterval: fileConfig.SamplingFrequency || 30,
  deviceId: fileConfig.Enterprise.DeviceId,
  queryDelay: fileConfig.QueryDelay || 500,
  retryCount: fileConfig.RetryCount || 5,
  useZigBee: fileConfig.UseZigBee,
  hostAddress: parseInt(fileConfig.ZigBeeId),
  baudRate: fileConfig.BaudRate,
  fixedDigits: fileConfig.FixedDigits || 3,
  modules: []
}

for (const md of fileConfig.Enterprise.Modules) {
  var mdb = {
    id: md.Id,
    dstAddress: parseInt(md.ZigBeeId),
    channels: []
  }

  for (const channel of md.Channels) {
    var chan = {
      id: channel.Id,
      name: channel.Name,
      unit: channel.DataUnit,
      mode: channel.ACOrDC,
      inputValueMin: channel.InputValueMin,
      inputValueMax: channel.InputValueMax,
      outputValueMin: channel.OutputValueMin,
      outputValueMax: channel.OutputValueMax
    }
    mdb.channels.push(chan)
  }
  config.modbus.modules.push(mdb)
}

function sanityCheck(cfg) {
  let ret = true
  for (let prop in cfg) {
    if (_.isArray(cfg[prop])) {
      for (let item of cfg[prop]) {
        if (_.isObject(item)) {
          ret = ret && sanityCheck(item)
        }
      }
    } else if (_.isObject(cfg[prop])) {
      ret = ret && sanityCheck(cfg[prop])
    } else {
      if (_.isUndefined(cfg[prop])) {
        ret = false
      }
    }
  }
  return ret
}

if (!sanityCheck(config)) {
  console.log('dasconfig error!!!')
}
